<!--
 * @Date: 2023-04-14 11:09:01
 * @LastEditTime: 2023-05-04 09:39:25
-->
<template>
  <a-modal
    v-model="visible"
    :title="modalTitleMap[modalType]"
    :maskClosable="false"
    :footer="null"
    :afterClose="onClose"
    @cancel="visible = false"
    destroyOnClose
  >
    <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="模块名称">
        <a-input v-model="form.module_name" placeholder="请输入模块名称" @pressEnter="submit" v-preventReClick="1000" />
      </a-form-model-item>

      <div class="btn_box">
        <a-button @click="submit" :loading="loading">{{ modalType ? '确认修改' : '确认新增' }}</a-button>
      </div>
    </a-form-model>
  </a-modal>
</template>

<script>
import { newModule, updateModule } from '@/api/module'

export default {
  name: 'NewModule',

  data () {
    return {
      visible: false,
      loading: false,
      modalType: 0,
      modalTitleMap: { 0: '新增模块', 1: '编辑模块' },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      form: { project_id: '', app_id: '', module_name: '', module_id: '' }
    }
  },

  mounted () {},

  methods: {
    // 打开弹窗
    open () {
      this.visible = true
    },
    // 关闭弹窗回调
    onClose () {
      this.visible = false

      this.form = { project_id: '', app_id: '', module_name: '', module_id: '' }
      this.modalType = 0
      this.$emit('close')
    },
    // 确认新增
    submit () {
      this.loading = true
      this.modalType ? this.updateModule() : this.newModule()
    },
    updateModule (isShowMsg = true) {
      const parmas = { ...this.form, type: 'update' }
      updateModule(this.form)
        .then((res) => {
          if (res.code === 200) {
            if (isShowMsg) this.$message.success(res.msg)
            this.$emit('success', parmas)
            this.onClose()
          } else this.$message.error(res.msg)
        })
        .finally(() => {
          this.loading = false
        })
    },
    newModule (isShowMsg = true) {
      const params = { ...this.form }
      delete params.project_id
      delete params.module_id
      newModule(params)
        .then((res) => {
          if (res.code === 200) {
            if (isShowMsg) this.$message.success(res.msg)

            const emitData = { ...res.data, project_id: this.form.project_id, type: 'new' }
            this.$emit('success', emitData)
            this.onClose()
          } else this.$message.error(res.msg)
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.btn_box {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
